package com.wds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wds.common.utils.BeanCopyUtils;
import com.wds.common.utils.RedisCacheUtils;
import com.wds.common.utils.SecurityUtils;
import com.wds.domain.JsonResult;
import com.wds.domain.entity.LoginUser;
import com.wds.domain.entity.User;
import com.wds.domain.vo.UserInfoVo;
import com.wds.exception.CustomException;
import com.wds.mapper.UserMapper;
import com.wds.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户表(User)表服务实现类
 *
 * @author wds
 * @since 2022-10-30 14:07:39
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisCacheUtils redisCache;

    @Override
    public JsonResult<Object> getUserInfo() {
        Long userId = SecurityUtils.getCurrentLoginUser().getUser().getId();
        User user = getById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copy(user, UserInfoVo.class);
        return JsonResult.ok(userInfoVo);
    }

    @Override
    public JsonResult<String> updateUserInfo(User user) {
        // 企图修改他人信息
        if (!SecurityUtils.getCurrentLoginUser().getUser().getId().equals(user.getId())) {
            return JsonResult.fail("501", "?系统错误");
        }

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, user.getId());
        updateWrapper.set(StringUtils.hasText(user.getAvatar()), User::getAvatar, user.getAvatar());
        updateWrapper.set(StringUtils.hasText(user.getNickName()), User::getNickName, user.getNickName());
        updateWrapper.set(StringUtils.hasText(user.getSex()), User::getSex, user.getSex());
//        暂时不能更改邮箱
//        updateWrapper.set(StringUtils.hasText(user.getEmail()), User::getEmail, user.getEmail());

        update(updateWrapper);

        // 更新redis中的用户信息 方便取出当前用户信息
        refreshRedisUserCache(SecurityUtils.getCurrentUserId());

        return JsonResult.ok();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public JsonResult<String> register(User user) {
        if(!StringUtils.hasText(user.getEmail())){
            throw new CustomException("邮箱不能为空");
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new CustomException("昵称不能为空");
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new CustomException("密码不能为空");
        }
        if(!StringUtils.hasText(user.getUsername())){
            throw new CustomException("用户名不能为空");
        }

//        数据校验
//        用户名不能重复，昵称不能重复
        if (hasUsername(user.getNickName())) {
            throw new CustomException("昵称已存在");
        }
        if (hasNickName(user.getUsername())) {
            throw new CustomException("用户名已存在");
        }
//        密码加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
//      过滤 、存入
        User SaveUser = new User();
        SaveUser.setEmail(user.getEmail());
        SaveUser.setNickName(user.getNickName());
        SaveUser.setPassword(encodePassword);
        SaveUser.setUsername(user.getUsername());

        save(SaveUser);
        return JsonResult.ok();
    }

    private boolean hasNickName(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, nickName);
        int count = count(queryWrapper);
        return count >0;
    }

    private boolean hasUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, username);
        int count = count(queryWrapper);
        return count >0;
    }

    /**
     * 刷新redis中的用户缓存
     *
     * @param userId 要刷新的用户ID
     */
    private void refreshRedisUserCache(Long userId) {
//        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        User user = getById(userId);
        if (user == null) {
            throw new CustomException("缓存或者数据库用户数据异常");
        }
        LoginUser loginUser = new LoginUser(user,null);
        redisCache.setCacheObject("LoginUser:" + userId, loginUser);

    }
}

